//
//  ILCarOtherViewController.m
//  ILife
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILCarOtherViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import <UIImageView+WebCache.h>
#import "ILCarouselModel.h"
#import "ILCarListModel.h"
#import "ILCarListTableViewCell.h"
#import "ILCarDetailViewController.h"
#import "AdView.h"
#import <MJRefresh.h>
#import "ILCarListNoPicTableViewCell.h"
#import "FMDatabase.h"

@interface ILCarOtherViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIImageView *topIV; // 顶部图片
@property (nonatomic, strong) UILabel *titleLabel; // 标题图片
@property (nonatomic, strong) NSMutableArray *carouselArr;
@property (nonatomic, strong) AdView *adView; // 轮播图
@property (nonatomic, strong) UIScrollView *carouselScrollView; // 
@property (nonatomic, assign) NSInteger page; // 参数
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, strong) NSMutableArray *carouselTitleArr;
@property (nonatomic, strong) NSMutableArray *carouselPicArr;
@property (nonatomic, strong) ILCarouselModel *carouselModel;
@property (nonatomic, strong) FMResultSet *carouselSet;
@property (nonatomic, strong) FMResultSet *listset;


@end

@implementation ILCarOtherViewController

#pragma mark - 懒加载
- (UIImageView *)topIV {
    if (!_topIV) {
        self.topIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 2)];
        [_topIV addSubview:self.titleLabel];
    }
    return _topIV;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH / 2 - 25, SCREEN_WIDTH, 25)];
    }
    return _titleLabel;
}

- (UITableView *)listTableView {
    if (!_listTableView) {
        self.listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    return _listTableView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (UIScrollView *)carouselScrollView {
    if (!_carouselScrollView) {
         self.carouselScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 2)];
    }
    return _carouselScrollView;
}


#pragma mark - 请求数据
- (void)requestDataWithNum:(NSInteger)num {
    // *****************************顶部图片*************************************
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // AFNetWork2.0以上要添加下面的话
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    NSDictionary *parameters = @{@"classId":self.classId,@"deviceid":@"011a189ac2a",@"platform":@"iOS"};
    [manager POST:POST_CAROUSEL_URL_STRING parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

        NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
        // 没图片的时候
        if ([str isEqualToString:@"<null>"]) {
            self.listTableView.tableHeaderView = nil;
        } else {
            [self.carouselArr removeAllObjects];
            [self.carouselPicArr removeAllObjects];
            [self.carouselTitleArr removeAllObjects];
            switch (num) {
                case 1:
                    [_dataBase executeUpdate:@"DELETE FROM CAROTHERONECAROUSEL"];
                    break;
                case 2:
                    [_dataBase executeUpdate:@"DELETE FROM CAROTHERTWOCAROUSEL"];
                    break;
                case 3:
                    [_dataBase executeUpdate:@"DELETE FROM CAROTHERTHREECAROUSEL"];
                    break;
                case 4:
                    [_dataBase executeUpdate:@"DELETE FROM CAROTHERFOURCAROUSEL"];
                    break;
                case 5:
                    [_dataBase executeUpdate:@"DELETE FROM CAROTHERFIVECAROUSEL"];
                    break;
                    
                default:
                    break;
            }
            for (NSDictionary *dataDic in responseObject[@"data"][@"focusList"]) {
                _carouselModel = [[ILCarouselModel alloc] init];
                [_carouselModel setValuesForKeysWithDictionary:dataDic];
                [self.carouselArr addObject:_carouselModel];
                [_carouselPicArr addObject:_carouselModel.picUrl];
                [_carouselTitleArr addObject:_carouselModel.title];

                NSLog(@"%@",_carouselModel.resourceLoc);
                self.titleLabel.text = _carouselModel.title;
                self.titleLabel.backgroundColor = [UIColor colorWithWhite:0.660 alpha:0.000];
                self.titleLabel.textColor = [UIColor whiteColor];
                self.titleLabel.font = [UIFont boldSystemFontOfSize:15];
                
                switch (num) {
                    case 1:
                        [_dataBase executeUpdate:@"INSERT INTO CAROTHERONECAROUSEL (picUrl, title, resourceLoc) VALUES (?,?,?)",_carouselModel.picUrl,_carouselModel.title,_carouselModel.resourceLoc];
                        break;
                    case 2:
                        [_dataBase executeUpdate:@"INSERT INTO CAROTHERTWOCAROUSEL (picUrl, title, resourceLoc) VALUES (?,?,?)",_carouselModel.picUrl,_carouselModel.title,_carouselModel.resourceLoc];
                        break;
                    case 3:
                        [_dataBase executeUpdate:@"INSERT INTO CAROTHERTHREECAROUSEL (picUrl, title, resourceLoc) VALUES (?,?,?)",_carouselModel.picUrl,_carouselModel.title,_carouselModel.resourceLoc];
                        break;
                    case 4:
                        [_dataBase executeUpdate:@"INSERT INTO CAROTHERFOURCAROUSEL (picUrl, title, resourceLoc) VALUES (?,?,?)",_carouselModel.picUrl,_carouselModel.title,_carouselModel.resourceLoc];
                        break;
                    case 5:
                        [_dataBase executeUpdate:@"INSERT INTO CAROTHERFIVECAROUSEL (picUrl, title, resourceLoc) VALUES (?,?,?)",_carouselModel.picUrl,_carouselModel.title,_carouselModel.resourceLoc];
                        break;
                        
                    default:
                        break;
                }
                
            }
            // 有一张图片
            if (self.carouselArr.count == 1) {
                self.listTableView.tableHeaderView = self.topIV;
                [_topIV sd_setImageWithURL:[NSURL URLWithString:_carouselModel.picUrl] placeholderImage:[UIImage imageNamed:@"ilife"]];
                
            }

            // 有多张图片
            if (self.carouselArr.count > 1) {
                self.carouselScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * self.carouselArr.count, SCREEN_WIDTH / 2);
                self.carouselScrollView.pagingEnabled = YES;
                self.listTableView.tableHeaderView = self.carouselScrollView;
                [self setUpCarousel];
               
            }
            
        }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"顶部图片请求失败,失败原因:%@",error);
        // 有多张图片
        if (self.carouselArr.count > 1) {
            self.carouselScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * self.carouselArr.count, SCREEN_WIDTH / 2);
            self.carouselScrollView.pagingEnabled = YES;
            self.listTableView.tableHeaderView = self.carouselScrollView;
            
        }

    }];
    // ***********************************下面的列表请求数据*************************************
    AFHTTPRequestOperationManager *listManager =[AFHTTPRequestOperationManager manager];
    // AFNetWork2.0以上要添加下面的话
    listManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    NSDictionary *listDataDic = @{@"classId":self.classId,@"deviceid":@"011a189ac2a",@"page":[NSString stringWithFormat:@"%ld",(long)self.page],@"platform":@"iOS",@"userId":@"0"};
    [listManager POST:POST_LIST_URL_STRING parameters:listDataDic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        if (self.page == 0) {
          [self.dataArr removeAllObjects];
        }
        switch (num) {
            case 1:
                [_dataBase executeUpdate:@"DELETE FROM CAROTHERONELIST"];
                break;
            case 2:
                [_dataBase executeUpdate:@"DELETE FROM CAROTHERTWOLIST"];
                break;
            case 3:
                [_dataBase executeUpdate:@"DELETE FROM CAROTHERTHREELIST"];
                break;
            case 4:
                [_dataBase executeUpdate:@"DELETE FROM CAROTHERFOURLIST"];
                break;
            case 5:
                [_dataBase executeUpdate:@"DELETE FROM CAROTHERFIVELIST"];
                break;
                
            default:
                break;
        }

        for (NSDictionary *listDic in responseObject[@"data"][@"newsList"]) {
            ILCarListModel *listModel = [[ILCarListModel alloc] init];
            [listModel setValuesForKeysWithDictionary:listDic];
            if (listModel.resourceLoc.length < 6) {
                [self.dataArr addObject:listModel];
            }
            switch (num) {
                case 1:
                    [_dataBase executeUpdate:@"INSERT INTO CAROTHERONELIST (title, publishTime, origin, readCount, picUrlList, resourceLoc) VALUES(?,?,?,?,?,?)",listModel.title,listModel.publishTime,listModel.origin,listModel.readCount,listModel.picUrlList,listModel.resourceLoc];
                    break;
                case 2:
                    [_dataBase executeUpdate:@"INSERT INTO CAROTHERTWOLIST (title, publishTime, origin, readCount, picUrlList, resourceLoc) VALUES(?,?,?,?,?,?)",listModel.title,listModel.publishTime,listModel.origin,listModel.readCount,listModel.picUrlList,listModel.resourceLoc];
                    break;
                case 3:
                    [_dataBase executeUpdate:@"INSERT INTO CAROTHERTHREELIST (title, publishTime, origin, readCount, picUrlList, resourceLoc) VALUES(?,?,?,?,?,?)",listModel.title,listModel.publishTime,listModel.origin,listModel.readCount,listModel.picUrlList,listModel.resourceLoc];
                    break;
                case 4:
                    [_dataBase executeUpdate:@"INSERT INTO CAROTHERFOURLIST (title, publishTime, origin, readCount, picUrlList, resourceLoc) VALUES(?,?,?,?,?,?)",listModel.title,listModel.publishTime,listModel.origin,listModel.readCount,listModel.picUrlList,listModel.resourceLoc];                    break;
                case 5:
                    [_dataBase executeUpdate:@"INSERT INTO CAROTHERFIVELIST (title, publishTime, origin, readCount, picUrlList, resourceLoc) VALUES(?,?,?,?,?,?)",listModel.title,listModel.publishTime,listModel.origin,listModel.readCount,listModel.picUrlList,listModel.resourceLoc];
                    break;
                    
                default:
                    break;
            }

        }
        [self.listTableView reloadData];
        [self.listTableView.header endRefreshing];
        [self.listTableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"列表数据请求失败,失败原因:%@",error);
       // 没网情况下刷新
       [self.listTableView reloadData];
    }];

}

- (void)setUpCarousel {
    //  轮播图
    self.adView = [AdView adScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 2) imageLinkURL:_carouselPicArr placeHoderImageName:nil pageControlShowStyle:(UIPageControlShowStyleCenter)];
    // 轮播图上面的title
    [_adView setAdTitleArray:_carouselTitleArr withShowStyle:(AdTitleShowStyleLeft)];
    [self.carouselScrollView addSubview:_adView];
#pragma mark - 轮播图的方法
    __block ILCarViewController *test = self.carVC;
    __block ILCarOtherViewController *carouselTest = self;
    self.adView.callBack = ^(NSInteger index,NSString * imageURL) {
        ILCarDetailViewController *detailVC = [[ILCarDetailViewController alloc] init];
        detailVC.collectionModel = [[ILCarCollectionModel alloc] init];
        ILCarouselModel *blockModel = carouselTest.carouselArr[index];
        detailVC.collectionModel.resourceLoc = blockModel.resourceLoc;
        detailVC.collectionModel.picUrl = blockModel.picUrl;
        detailVC.collectionModel.title = blockModel.title;
        [test.navigationController pushViewController:detailVC animated:YES];
    };

}

#pragma mark - 手势
- (void)enterDetail:(UITapGestureRecognizer *)tapGesture {
    ILCarDetailViewController *detailVC = [[ILCarDetailViewController alloc] init];
    detailVC.collectionModel = [[ILCarCollectionModel alloc] init];
    ILCarouselModel *model = self.carouselArr[0];
    detailVC.collectionModel.resourceLoc = model.resourceLoc;
    detailVC.collectionModel.picUrl = model.picUrl;
    detailVC.collectionModel.title = model.title;
    [_carVC.navigationController pushViewController:detailVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
#pragma mark - 因为每次进来要重新判断 不能用懒加载
    _carouselArr = [NSMutableArray array];
    _carouselTitleArr = [NSMutableArray array];
    _carouselPicArr = [NSMutableArray array];
    self.view.backgroundColor= [UIColor whiteColor];
    // Do any additional setup after loading the view.
    self.page = 0;
    self.view = self.listTableView;
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    [self.listTableView registerClass:[ILCarListTableViewCell class] forCellReuseIdentifier:@"listCell"];
    [self.listTableView registerClass:[ILCarListNoPicTableViewCell class] forCellReuseIdentifier:@"noPic"];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(enterDetail:)];
    self.topIV.userInteractionEnabled = YES;
    [self.topIV addGestureRecognizer:tapGesture];
    self.classId = @"0";
    
    [self refresh];
    
}

/**
 *  保存数据
 */
- (void)saveOtherDataWithNum:(NSInteger)num {
    _dataBase = [FMDatabase databaseWithPath:FILEPATH];
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        switch (num) {
            case 1:
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERONECAROUSEL (picUrl text, title text, resourceLoc text)"];
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERONELIST (title text, publishTime text, origin text, readCount text, picUrlList text, resourceLoc text)"];
                break;
            case 2:
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERTWOCAROUSEL (picUrl text, title text, resourceLoc text)"];
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERTWOLIST (title text, publishTime text, origin text, readCount text, picUrlList text, resourceLoc text)"];
                break;
            case 3:
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERTHREECAROUSEL (picUrl text, title text, resourceLoc text)"];
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERTHREELIST (title text, publishTime text, origin text, readCount text, picUrlList text, resourceLoc text)"];

                break;
            case 4:
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERFOURCAROUSEL (picUrl text, title text, resourceLoc text)"];
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERFOURLIST (title text, publishTime text, origin text, readCount text, picUrlList text, resourceLoc text)"];
                break;
            case 5:
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERFIVECAROUSEL (picUrl text, title text, resourceLoc text)"];
                [_dataBase executeUpdate:@"CREATE TABLE CAROTHERFIVELIST (title text, publishTime text, origin text, readCount text, picUrlList text, resourceLoc text)"];
                break;
            default:
                break;
        }
        
    } else {
        NSLog(@"数据库打开失败");
    }
    // 轮播图
    switch (num) {
        case 1:
            _carouselSet =[_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERONECAROUSEL"];
            break;
        case 2:
            _carouselSet =[_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERTWOCAROUSEL"];
            break;
        case 3:
            _carouselSet =[_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERTHREECAROUSEL"];
            break;
        case 4:
            _carouselSet =[_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERFOURCAROUSEL"];
            break;
        case 5:
            _carouselSet =[_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERFIVECAROUSEL"];
            break;
            
        default:
            break;
    }
    
    [self.carouselArr removeAllObjects];
    [self.carouselPicArr removeAllObjects];
    [self.carouselTitleArr removeAllObjects];

    while ([_carouselSet next]) {
        NSString *picUrl = [_carouselSet stringForColumn:@"picUrl"];
        NSString *title = [_carouselSet stringForColumn:@"title"];
        NSString *resourceLoc = [_carouselSet stringForColumn:@"resourceLoc"];
        ILCarouselModel *carouselModel = [[ILCarouselModel alloc] init];
        carouselModel.picUrl = picUrl;
        carouselModel.title = title;
        carouselModel.resourceLoc = resourceLoc;
        
        [self.carouselPicArr addObject:carouselModel.picUrl];
        [self.carouselTitleArr addObject:carouselModel.title];
        [self.carouselArr addObject:carouselModel];
    }
    [_carouselSet close];

    // 判断网络是否连接
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable) {
            if (self.carouselArr.count > 1) {
                [self setUpCarousel];
            } else if (self.carouselArr.count == 1) {
            ILCarouselModel *carouselModel = self.carouselArr[0];
            [_topIV sd_setImageWithURL:[NSURL URLWithString:carouselModel.picUrl]];
            self.titleLabel.text = carouselModel.title;
            self.titleLabel.backgroundColor = [UIColor colorWithWhite:0.660 alpha:0.000];
            self.titleLabel.textColor = [UIColor whiteColor];
            self.titleLabel.font = [UIFont boldSystemFontOfSize:15];
            self.listTableView.tableHeaderView = self.topIV;
            }
        }
    }];
    [manager.reachabilityManager startMonitoring];
 
    switch (num) {
        case 1:
            _listset = [_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERONELIST"];
            break;
        case 2:
            _listset = [_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERTWOLIST"];
            break;
        case 3:
            _listset = [_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERTHREELIST"];
            break;
        case 4:
            _listset = [_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERFOURLIST"];
            break;
        case 5:
            _listset = [_dataBase executeQueryWithFormat:@"SELECT *FROM CAROTHERFIVELIST"];
            break;
            
        default:
            break;
    }

    
    while ([_listset next]) {
        NSString *title = [_listset stringForColumn:@"title"];
        NSString *publishTime = [_listset stringForColumn:@"publishTime"];
        NSString *origin = [_listset stringForColumn:@"origin"];
        NSString *readCount = [_listset stringForColumn:@"readCount"];
        NSString *picUrlList = [_listset stringForColumn:@"picUrlList"];
        NSString *resourceLoc = [_listset stringForColumn:@"resourceLoc"];
        ILCarListModel *listModel = [[ILCarListModel alloc] init];
        listModel.title = title;
        listModel.publishTime = publishTime;
        listModel.origin = origin;
        listModel.readCount = readCount;
        listModel.picUrlList = picUrlList;
        listModel.resourceLoc = resourceLoc;
        [self.dataArr addObject:listModel];
    }
    [_listset close];
}




// 上提加载 下拉刷新
- (void)refresh {
    // 下拉刷新
    self.listTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
    }];
    self.listTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
    // 上提加载
    self.listTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
    }];
    self.listTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

- (void)headerRefresh {
    self.page = 0;
    [self requestDataWithNum:self.num];
}

- (void)footerRefresh {
    self.page += 1;
    [self requestDataWithNum:self.num];
}

#pragma mark - tableView的代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ILCarListModel *listModel = self.dataArr[indexPath.row];
    if ([listModel.picUrlList isEqualToString:@""]) {
        ILCarListNoPicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noPic" forIndexPath:indexPath];
        cell.listModel = self.dataArr[indexPath.row];
        return cell;
    }
    ILCarListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
    
    cell.listModel = self.dataArr[indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ILCarDetailViewController *detailVC = [[ILCarDetailViewController alloc] init];
    detailVC.collectionModel = [[ILCarCollectionModel alloc] init];
    ILCarListModel *model = self.dataArr[indexPath.row];
    detailVC.collectionModel.resourceLoc = model.resourceLoc;
    detailVC.collectionModel.title = model.title;
    detailVC.collectionModel.picUrl = model.picUrlList;
    [_carVC.navigationController pushViewController:detailVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SCREEN_WIDTH / 4 + 10;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
